//编译：
//运行：

#include "ConnectionPool.h"
#include "Connection.h"
using namespace std;

//单线程测试用例
void SingleConnection(){
    time_t begin = clock();
    for(int i=0;i<10000;i++){
        ConnectionPool* cp = ConnectionPool::getConnectionPool();
        std::shared_ptr<Connection> sp = cp->getConnection();
        char sql[1024] = {0};
		sprintf(sql, "insert into user(name,age,sex) values('%s','%d','%s')",
			"zhangsan", 20, "male");
        sp->update(sql);
    }
    std::cout<<"SingleConnection use time:  "<<(time_t)(clock()-begin)<<std::endl;
}

void SingleNoConnection(){
    time_t begin = clock();
    for(int i=0;i<10000;i++){
        Connection conn;
        char sql[1024] = {0};
		sprintf(sql, "insert into user(name,age,sex) values('%s','%d','%s')",
			"zhangsan", 20, "male");
        conn.connect("127.0.0.1", 1478, "root", "123456", "mysql");
        conn.update(sql);
    }
    std::cout<<"SingleConnection use time:  "<<(time_t)(clock()-begin)<<std::endl;
}

void th_func(){
    for(int i=0;i<2500;i++){
        ConnectionPool* cp = ConnectionPool::getConnectionPool();
        shared_ptr<Connection> sp = cp->getConnection();
        char sql[1024] = {0};
		sprintf(sql, "insert into user(name,age,sex) values('%s','%d','%s')",
			"zhangsan", 20, "male");
        if(sp == nullptr){
            cout<<"sp is empty"<<endl;
            continue;
        }
        sp->update(sql);        
    }
}

void th_func2(){
    for(int i=0;i<2500;i++){
        Connection conn;
        char sql[1024] = {0};
		sprintf(sql, "insert into user(name,age,sex) values('%s','%d','%s')",
			"zhangsan", 20, "male");
        conn.connect("127.0.0.1", 1478, "root", "123456", "mysql");
        conn.update(sql);        
    }
}

void MutiWithConnection(){
    time_t begin = clock();    
    thread t1(th_func);
    thread t2(th_func);
    thread t3(th_func);
    thread t4(th_func);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    std::cout<<"SingleConnection use time:  "<<(time_t)(clock()-begin)<<std::endl;
}

void MutiNoConnection(){
    time_t begin = clock();    
    thread t1(th_func2);
    thread t2(th_func2);
    thread t3(th_func2);
    thread t4(th_func2);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
    std::cout<<"SingleConnection use time:  "<<(time_t)(clock()-begin)<<std::endl;
}

auto main(int argc,char* argv[]) -> int{
    SingleNoConnection();
    return 0;
}